package opt.power.springdemo.interceptor;

import lombok.extern.slf4j.Slf4j;
import opt.power.springdemo.config.Constants;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 用来处理token的adapter
 *
 * @author xuliduo
 * @date 2017/11/15
 * @description class AccessTokenVerifyInterceptor
 */
@Slf4j
@Component
public class AccessTokenVerifyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if (!request.getMethod().equals(HttpMethod.POST.toString())) {
//            return true;
//        }
        String token = Optional.ofNullable(request.getHeader(Constants.TOKEN)).orElse("");
        log.debug("token->{}", token);
        //TODO check token
        boolean flag = !"".equals(token);
        if (!flag) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().print("AccessToken ERROR");
        }

        return flag;
    }
}
